package pdm.h_2011_01;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.ArrayList;


import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


class City implements Comparable<City>
{
	private String name_;
	
	public City(String name)
	{
		name_ = name;
	}
	
	public String getName()
	{
		return name_;
	}
	
	public String toString()
	{
		return name_;
	}
	
	public int compareTo(City c) {
	  return name_.compareTo(c.getName());
	}
}


class CityListAdapter extends BaseAdapter
{
	private Activity context_;
	ArrayList<City> cities_;

	public CityListAdapter (Activity context)
	{
		context_ = context;
		cities_ = new ArrayList<City>();
	}

	public View getView (int position, View convertView, ViewGroup list) 
	{
		// functia trebuie sa intoarca view-ul de pe pozitia position din lista
		// convertView este un element din lista ce nu mai este vizibil si poate fi convertit
		View element;
		LayoutInflater inflater = context_.getLayoutInflater();
		element = inflater.inflate(R.layout.city, null);

		TextView cityTV = (TextView)element.findViewById(R.id.city_name);


		cityTV.setText(cities_.get(position).getName());

		return element;
	}

    public int getCount ()
    {
		// intaorce nr de elemente din lista
		return cities_.size ();
	}

    public void clear()
    {
    	cities_.clear();
		this.notifyDataSetChanged();
    }
    
	public Object getItem(int position) 
	{
		// intoarce elementul de pe pozitia position din model
		return cities_.get(position);
	}

	public long getItemId(int position) 
	{
		// fiecare element din lista poate avea un id, nu este insa obligatoriu
		return 0;
	}

	public void addCity(String name)
	{
		int comp;
		
		City c = new City(name.toUpperCase());
		
		System.out.println("Aici sunt");
		
		for (int i = 0; i < cities_.size(); i++) {
			comp = cities_.get(i).compareTo(c);
			System.out.printf("%d %d\n", i, comp);
			if (comp == 0) {
				System.out.println("Doamne fereste e deja");
				return;
			}
			if (comp > 0) {
				cities_.add (i, c);

				System.out.println("Sug pula");
				this.notifyDataSetChanged();
				return;
			}
		}
		
		cities_.add(c);
		
		// acesta functie deterimina adaptorul sa ceara listei sa reafiseze continutul
		this.notifyDataSetChanged();
	}
	
	public void removeCity(City c)
	{
		cities_.remove(c);
		
		// acesta functie deterimina adaptorul sa ceara listei sa reafiseze continutul
		this.notifyDataSetChanged();
	}
}


public class Pdm_h_2011_01_activity extends ListActivity 
		implements View.OnClickListener{
    /** Called when the activity is first created. */
	
	Button addButton_;
	CityListAdapter adapter;
	Intent addIntent_;
	
	String cacheFile = "city_list.txt";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        
        adapter = new CityListAdapter (this);
        setContentView (R.layout.main);
        setListAdapter (adapter);
        
		Log.println (Log.DEBUG, "activity", "Start main activity");  
        
        addButton_ = (Button) findViewById(R.id.addButon);
        addButton_.setOnClickListener(this);
        
        addIntent_ = new Intent ();
        addIntent_.setClass(this, AddCity.class); 
        
        
        getListView().setOnItemLongClickListener(new OnItemLongClickListener() 
		{
			public boolean onItemLongClick(AdapterView<?> listAdapter, View view,
					int position, long id) 
			{
		        City c = (City) adapter.getItem (position);
		        
		        adapter.removeCity(c);
				return true;
			}
		});  
        
        
    	try {
	    	InputStream in = openFileInput(cacheFile);
	    	if (in != null) {
		    	InputStreamReader tmp = new InputStreamReader(in);
		    	BufferedReader reader = new BufferedReader(tmp);
		    	String str;
 
 
		    	while ((str = reader.readLine()) != null) {
		    		adapter.addCity(str);
		    	}
		    	in.close();
 
	    	}
    	} catch (java.io.FileNotFoundException e) {
    		// that's OK, we probably haven't created it yet
    	} catch (Throwable t) {
    	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    	}
    }
    
 
    public void onPause() {
    	super.onPause();
    	try {
	    	OutputStreamWriter out = new OutputStreamWriter(openFileOutput(cacheFile, 0));
	    	City c;
	    	
	    	for (int i = 0; i < adapter.getCount(); i++) {
	    		c = (City) adapter.getItem(i);
	    		out.write(c.getName() + "\n");
	    	}

	    	
	    	out.close();
	    	
	    	
    	} catch (Throwable t) {
    	Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
    	}
    }    
    
    
	public void onClick(View v) {
		Log.println (Log.DEBUG, "buton", "Add new city");

		startActivityForResult (addIntent_, 100);
	}
	
    @Override
    public void onActivityResult (int requestCode, int responseCode, Intent responseIntent)
    {


    	if (requestCode == 100)
    	{
    		// s-a apasat butonul Add
    		if (responseCode==1)
    		{
    			String city = responseIntent.getStringExtra("city");
    			
    			Log.println (Log.DEBUG, "intent", "Add" + city);
    	    	
    			
    			adapter.addCity(city);
    		}
    		// s-a apasat butonul Cancel
    		else 
    			if (responseCode==0)
    			{
        			Log.println (Log.DEBUG, "intent", "Cancel");    				
    			}
    	}
    }
    
    @Override
    public void onListItemClick (ListView list, View v, int position, long id)
    {
        City c = (City) adapter.getItem (position);
        
        Intent intent = new Intent ();
         
        intent.setClass(this, WeatherInfoActivity.class);
         
        // setam parametrul doi parametrii, un String cu numele "nume" si un numar cu numele "numar"
        intent.putExtra("city", c.getName());
         
        // componenta de destinatie stim ca este o activitate, deci emitem Intent-ul cu startActivity
        // atentie, functia startActivity intoarce imediat, urmand ca sistemul sa porneasca la un moment dat fereastra (vezi Laboratorul 2)
        startActivity (intent);        
    }
}